package com.go.smsautosender;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.telephony.SmsManager;
import android.text.InputFilter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.go.smsautosender.data.Const;
import com.go.smsautosender.util.ByteLengthFilter;
import com.go.smsautosender.util.MMS;

public class MainActivity extends Activity {
	
	private static final int PICK_FROM_TEXTFILE = 0;
	private static final int PICK_FROM_CAMERA = 1;
	private static final int PICK_FROM_ALBUM = 2;
	private static final int CROP_FROM_CAMERA = 3;
	
	private final int CHECK_COUNT = 100;
	private final int MMS_RANGE = 5;
	
	int testCount = 0;
	Intent intent;
	
	private TextView txtTotal, txtPage, txtImageName;
	private EditText editOnceCount, editCurrentCount, editOnceCheck, editLastCheck, editSendView, editStartSetNum;
	private CheckBox checkOnceCheck, checkLastCheck;
	private Button btnSend, btnStop, btnAddImage;
	private ImageView imageIcon;
	
	private SMSSendThread mSMSSender;
	private MMSSendThread mMMSSender;
	private PendingIntent mSendPI;
	
	private int mTotal, mPages, mCount, mResult = 0;
	private boolean mIsStop = false, mIsReceive = false, mOnceCheck = false, mLastCheck = false;
	
	private Dialog dialog;
	
	private Uri mImageCaptureUri;
	private AlertDialog mDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		
		
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		
		VerifyUser verify = new VerifyUser(this);

		if(verify.verify()) {

		} else {
			finish();
		}
		
		txtTotal = (TextView)findViewById(R.id.txt_total);
		txtPage = (TextView)findViewById(R.id.txt_page);
		txtImageName = (TextView)findViewById(R.id.txt_imageName);
		imageIcon = (ImageView)findViewById(R.id.icon_image);
		
		editOnceCount = (EditText)findViewById(R.id.edit_onceCount);
		editCurrentCount = (EditText)findViewById(R.id.edit_currentCount);
		editOnceCheck = (EditText)findViewById(R.id.edit_onceCheckPhoneNumber);
		editLastCheck = (EditText)findViewById(R.id.edit_lastCheckPhoneNumber);
		editSendView = (EditText)findViewById(R.id.edit_sendView);
		
		// 80byte까지만 입력 가능하도록 필터설정 ( byte로 따지는거 맞나모르게씀 헬프미? ) yoonhwa
		InputFilter[] byteFilter = new InputFilter[] { new ByteLengthFilter(80, "KSC5601") };
		editSendView.setFilters(byteFilter);
		
		checkOnceCheck = (CheckBox)findViewById(R.id.check_onceCheck);
		checkLastCheck = (CheckBox)findViewById(R.id.check_lastCheck);
		
		checkOnceCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				
				mOnceCheck = isChecked;
				
				if(isChecked) {
					editOnceCheck.setEnabled(true);
				} else {
					editOnceCheck.setEnabled(false);
				}
			}
		});
		checkLastCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				
				mLastCheck = isChecked;
				
				if(isChecked) {
					editLastCheck.setEnabled(true);
				} else {
					editLastCheck.setEnabled(false);
				}
			}
		});
		
		btnSend = (Button) findViewById(R.id.send);
		btnStop = (Button) findViewById(R.id.stop);
		btnAddImage = (Button) findViewById(R.id.btn_addImage);
		
		mSMSSender = new SMSSendThread();
		btnSend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				if(editOnceCount.getText().toString().equals("")) {
					Toast.makeText(MainActivity.this, "1회전송건수를 입력하세요.", Toast.LENGTH_SHORT).show();
					return;
				}
				if(mOnceCheck && editOnceCheck.getText().toString().equals("")) {
					Toast.makeText(MainActivity.this, "1회 확인을 입력하세요.", Toast.LENGTH_SHORT).show();
					return;
				}
				if(mLastCheck && editLastCheck.getText().toString().equals("")) {
					Toast.makeText(MainActivity.this, "최종 확인을 입력하세요.", Toast.LENGTH_SHORT).show();
					return;
				}
				
				if(Const.PhoneBook == null || Const.PhoneBook.size() < 1) {
					Toast.makeText(MainActivity.this, "전송할 전화번호가 없습니다.", Toast.LENGTH_SHORT).show();
					return;
				}
				if(editSendView.getText().toString().equals("") || editSendView.getText() == null) {
					Toast.makeText(MainActivity.this, "메시지를 입력 해 주세요.", Toast.LENGTH_SHORT).show();
					return;
				}
				
				mCount = 0;
				// SMS
				if(txtImageName.getText().toString().equals("")) {
					if(mSMSSender == null) {
						mSMSSender = new SMSSendThread();
					} else {
						mSMSSender = null;
						SystemClock.sleep(100);
						mSMSSender = new SMSSendThread();
					}
					try {
						mPages = mTotal / Integer.valueOf(editOnceCount.getText().toString()) + 1;
						txtPage.setText("페이지 : " + String.valueOf(mPages));
						mSMSSender.execute();
					} catch(Exception e) {
						e.printStackTrace();
					}
				// MMS
				} else {
					if(mMMSSender == null) {
						mMMSSender = new MMSSendThread();
					} else {
						mMMSSender = null;
						SystemClock.sleep(100);
						mMMSSender = new MMSSendThread();
					}
					try {
						mPages = mTotal / Integer.valueOf(editOnceCount.getText().toString()) + 1;
						txtPage.setText("페이지 : " + String.valueOf(mPages));
						mMMSSender.execute();
					} catch(Exception e) {
						e.printStackTrace();
					}
					
//					Uri mmsUri = Uri.parse("mmsto:");
//					Intent sendIntent = new Intent(Intent.ACTION_VIEW, mmsUri);  
//			        sendIntent.addCategory("android.intent.category.DEFAULT");
//			        sendIntent.addCategory("android.intent.category.BROWSABLE");
//			        sendIntent.putExtra("address", "01033886876");
//			        sendIntent.putExtra("exit_on_sent", true);
//			        sendIntent.putExtra("subject", "dfdfdf");
//			        sendIntent.putExtra("sms_body", "dfdfsdf");
//			        Uri dataUri = Uri.parse(""+mImageCaptureUri);
//			        sendIntent.putExtra(Intent.EXTRA_STREAM, dataUri);
//			 
//			        startActivity(sendIntent);
			        
//			        Uri mmsUri = Uri.parse("mmsto:");
//					Intent it = new Intent(Intent.ACTION_SEND);   
//			        it.putExtra(Intent.EXTRA_STREAM, mImageCaptureUri);   
//			        it.setType("image/*");
//			        it.putExtra("address", "01033886876, 01037522285");
//			        it.putExtra("subject", editSendView.getText().toString());
//			        it.putExtra("sms_body", "dfdfsdf");
			        // 삼성 단말에서만 허용 ( 앱 선택 박스 없이 호출 )
//			      it.setComponent(new ComponentName("com.sec.mms", "com.sec.mms.Mms"));
//			        startActivity(it); 
				}
			}
		});
		btnStop.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				if(mSMSSender != null) {
					mSMSSender.stop();
					mSMSSender = null;
				}
				if(mMMSSender != null) {
					mMMSSender.stop();
					mMMSSender = null;
				}
			}
		});
		
		btnAddImage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
//				mDialog = createDialog();
//				mDialog.show();
				if(btnAddImage.getText().toString().equals("첨부"))
					doTakeAlbumAction();
				else {
					txtImageName.setText("");
					imageIcon.setImageBitmap(null);
					btnAddImage.setText("첨부");
				}
					
				
			}
			
		});
		
		txtTotal.setText("전체 : 0");
		txtPage.setText("페이지 : 0");
		editOnceCount.setText("5");
		editOnceCheck.setEnabled(false);
		editLastCheck.setEnabled(false);
		checkOnceCheck.setChecked(false);
		checkLastCheck.setChecked(false);
		initBroadCast();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0,0,0, "파일 선택");
		menu.add(0,1,0, "시작 지점 설정");
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
		
		switch(item.getItemId()) {
		case 0:
			String ext = Environment.getExternalStorageState();
			
			if (ext.equals(Environment.MEDIA_MOUNTED)) {
				startActivityForResult((new Intent(MainActivity.this, FileListViewActivity.class)), PICK_FROM_TEXTFILE);
			} else {
				Toast.makeText(MainActivity.this, "SD카드를 확인 해 주세요.", Toast.LENGTH_SHORT).show();
			}
			break;
		case 1:
			if(mSMSSender != null) {
				mSMSSender.stop();
				mSMSSender = null;
			}
			if(mMMSSender != null) {
				mMMSSender.stop();
				mMMSSender = null;
			}
			showStartSetDialog();
			break;
		}
		
		
		
		
		return super.onOptionsItemSelected(item);
    }
	
	/** 
	 * 다이얼로그 생성
	 */
	private AlertDialog createDialog() {
		final View innerView = getLayoutInflater().inflate(R.layout.image_crop_row, null);

		Button camera = (Button)innerView.findViewById(R.id.btn_camera_crop);
		Button gellary = (Button)innerView.findViewById(R.id.btn_gellary_crop);

		camera.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				doTakePhotoAction();
				setDismiss(mDialog);
			}
		});

		gellary.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				doTakeAlbumAction();
				setDismiss(mDialog);
			}
		});

		AlertDialog.Builder ab = new AlertDialog.Builder(this);
		ab.setTitle("이미지 Crop");
		ab.setView(innerView);

		return  ab.create();
	}

	/** 
	 * 다이얼로그 종료 
	 */
	private void setDismiss(AlertDialog dialog){
		if(dialog!=null&&dialog.isShowing()){
			dialog.dismiss();
		}
	}
	
	private void showStartSetDialog() {

		dialog = new Dialog(this);
		dialog.setContentView(R.layout.startsetdialog);
		dialog.setTitle("시작 지점 설정");
		
		editStartSetNum = (EditText)dialog.findViewById(R.id.edit_startNum);
    			
		dialog.findViewById(R.id.btn_ok).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						mCount = Integer.valueOf(editStartSetNum.getText().toString());
						editCurrentCount.setText(String.valueOf(mCount));
						dialog.dismiss();
					}
				});
		
		dialog.findViewById(R.id.btn_cancel).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
							dialog.cancel();
					}
				});
		
		dialog.show();

    }
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		if(resultCode != RESULT_OK)
			return;
		
		switch(requestCode) { 
		case PICK_FROM_TEXTFILE:
		{
			
			String filePath = data.getStringExtra("path");
		
			if(filePath != null && !filePath.equals("")) {
				readTextFile(filePath);
				
				setViewInfo();
			}
			
			break;
		}
			
		case PICK_FROM_ALBUM:
		{
			Log.d("", "PICK_FROM_ALBUM");
			
			// 이후의 처리가 카메라와 같으므로 일단  break없이 진행합니다.
			// 실제 코드에서는 좀더 합리적인 방법을 선택하시기 바랍니다.
			mImageCaptureUri = data.getData();
			File original_file = getImageFile(mImageCaptureUri);
			
			mImageCaptureUri = createSaveCropFile();
			File cpoy_file = new File(mImageCaptureUri.getPath()); 

			// SD카드에 저장된 파일을 이미지 Crop을 위해 복사한다.
			copyFile(original_file , cpoy_file);
		}

		case PICK_FROM_CAMERA:
		{
			Log.d("", "PICK_FROM_CAMERA"); 

			// 이미지를 가져온 이후의 리사이즈할 이미지 크기를 결정합니다.
			// 이후에 이미지 크롭 어플리케이션을 호출하게 됩니다.

			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(mImageCaptureUri, "image/*"); 
			
			// Crop한 이미지를 저장할 Path
			intent.putExtra("output", mImageCaptureUri);
			
			// Return Data를 사용하면 번들 용량 제한으로 크기가 큰 이미지는
			// 넘겨 줄 수 없다.
//			intent.putExtra("return-data", true); 
			startActivityForResult(intent, CROP_FROM_CAMERA);

			break;
		}
		
		case CROP_FROM_CAMERA:
		{
			Log.w("", "CROP_FROM_CAMERA");
			
			// Crop 된 이미지를 넘겨 받습니다.
			Log.w("", "mImageCaptureUri = " + mImageCaptureUri);

			String full_path = mImageCaptureUri.getPath();
			String photo_path = full_path.substring(4, full_path.length());
			
			Log.w("", "비트맵 Image path = "+photo_path);
			
			Bitmap photo = BitmapFactory.decodeFile(photo_path);
			txtImageName.setText(photo_path);
			imageIcon.setImageBitmap(photo);
			btnAddImage.setText("삭제");

			break;
		}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if(mSMSSender != null) {
			mSMSSender.stop();
		}
		mSMSSender = null;
		
		if(mMMSSender != null) {
			mMMSSender.stop();
		}
		mMMSSender = null;
		
		unregisterReceiver(mSentReceiver);
	}
	
	/**
	 * 카메라 호출 하기
	 */
	private void doTakePhotoAction()
	{
		Log.i("", "doTakePhotoAction()");
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		// Crop된 이미지를 저장할 파일의 경로를 생성
		mImageCaptureUri = createSaveCropFile();
		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
		startActivityForResult(intent, PICK_FROM_CAMERA);
	}

	/**
	 * 앨범 호출 하기
	 */
	private void doTakeAlbumAction()
	{
		Log.i("", "doTakeAlbumAction()");
		// 앨범 호출
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
		startActivityForResult(intent, PICK_FROM_ALBUM);
	}
	
	/**
	 * Crop된 이미지가 저장될 파일을 만든다.
	 * @return Uri
	 */
	private Uri createSaveCropFile(){
		Uri uri;
		String url = "tmp_" + String.valueOf(System.currentTimeMillis()) + ".jpg";
		uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), url));
		return uri;
	}


	/**
	 * 선택된 uri의 사진 Path를 가져온다.
	 * uri 가 null 경우 마지막에 저장된 사진을 가져온다.
	 * @param uri
	 * @return
	 */
	private File getImageFile(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		if (uri == null) {
			uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		}

		Cursor mCursor = getContentResolver().query(uri, projection, null, null, 
				MediaStore.Images.Media.DATE_MODIFIED + " desc");
		if(mCursor == null || mCursor.getCount() < 1) {
			return null; // no cursor or no record
		}
		int column_index = mCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		mCursor.moveToFirst();

		String path = mCursor.getString(column_index);

		if (mCursor !=null ) {
			mCursor.close();
			mCursor = null;
		}

		return new File(path);
	}
	
	/**
	 * 파일 복사
	 * @param srcFile : 복사할 File
	 * @param destFile : 복사될 File
	 * @return
	 */
	public static boolean copyFile(File srcFile, File destFile) {
		boolean result = false;
		try {
			InputStream in = new FileInputStream(srcFile);
			try {
				result = copyToFile(in, destFile);
			} finally  {
				in.close();
			}
		} catch (IOException e) {
			result = false;
		}
		return result;
	}

	/**
	 * Copy data from a source stream to destFile.
	 * Return true if succeed, return false if failed.
	 */
	private static boolean copyToFile(InputStream inputStream, File destFile) {
		try {
			OutputStream out = new FileOutputStream(destFile);
			try {
				byte[] buffer = new byte[4096];
				int bytesRead;
				while ((bytesRead = inputStream.read(buffer)) >= 0) {
					out.write(buffer, 0, bytesRead);
				}
			} finally {
				out.close();
			}
			return true;
		} catch (IOException e) {
			return false;
		}
	}
	
	
	/**
	 * sd카드에서 선택 한 텍스트파일을 읽는다.
	 * @param path
	 * @return
	 */
	public void readTextFile(String path) {
		BufferedReader br = null;
		
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
			
			String buffer = null;
			Const.PhoneBook = new ArrayList<String>();
			
			while((buffer = br.readLine()) != null) {
				Const.PhoneBook.add(buffer);
			}
		} catch (FileNotFoundException e) {
			String exceptionMessage = "존재하지 않는 파일입니다.";
		    Toast.makeText(MainActivity.this, exceptionMessage, Toast.LENGTH_SHORT).show();
		    e.printStackTrace();
		}
		
		// 입출력 관련된 예외 처리
		catch (IOException e) {
		    String exceptionMessage = "파일을 읽는 도중에 오류가 발생했습니다.";
		    Toast.makeText(MainActivity.this, exceptionMessage, Toast.LENGTH_SHORT).show();
		    e.printStackTrace();
		}
		catch(Exception e) {
			
		}
	}
	
	private void initBroadCast() {
		String SENT = "SMS_SENT";

		mSendPI = PendingIntent.getBroadcast(MainActivity.this, 0, 
				new Intent(SENT), 0);

		registerReceiver(mSentReceiver, new IntentFilter(SENT));
	}
	
	private BroadcastReceiver mSentReceiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			switch(getResultCode()) {
			case Activity.RESULT_OK:
			case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
			case SmsManager.RESULT_ERROR_NO_SERVICE:
			case SmsManager.RESULT_ERROR_NULL_PDU:
			case SmsManager.RESULT_ERROR_RADIO_OFF:
				mIsReceive = true;
				break;
			}
			
			Log.d("test", "getResultCode :: "+getResultCode());
			
			mResult = getResultCode();
		}
	};
	
	private void setViewInfo() {
		if(Const.PhoneBook.size() < 1) {
			Toast.makeText(MainActivity.this, "전송할 전화번호를 읽지 못했습니다.", Toast.LENGTH_SHORT).show();
			return;
		}
		if(editOnceCount.getText().toString().equals("")) {
			Toast.makeText(MainActivity.this, "1회전송건수를 입력해주세요.", Toast.LENGTH_SHORT).show();
			return;
		}
		
		mTotal = Const.PhoneBook.size();
		mPages = mTotal / Integer.valueOf(editOnceCount.getText().toString()) + 1;
		mCount = 0;
		
		txtTotal.setText("전체 : " + String.valueOf(mTotal));
		txtPage.setText("페이지 : " + String.valueOf(mPages));
	}
	
	class SMSSendThread extends AsyncTask<String, Integer, Integer> {
		private boolean stop = false;
		
		@Override
		protected Integer doInBackground(String... params) {
			// TODO Auto-generated method stub
			SmsManager sms = SmsManager.getDefault();
			String text = editSendView.getText().toString();
			String onceCheck = null;
			String lastCheck = null;
			
			if(mLastCheck) {
				lastCheck = editLastCheck.getText().toString();
			}
			if(mOnceCheck) {
				onceCheck = editOnceCheck.getText().toString();
			}
			
			int page = Integer.valueOf(editOnceCount.getText().toString());
			
			while(!stop) {
				Log.d("test", mCount+"::PhoneBook");
				sms.sendTextMessage(Const.PhoneBook.get(mCount), null, text, mSendPI, null);
				
				publishProgress(mCount+1);
				
				if((mCount > 0) && (mCount % CHECK_COUNT == 0)) {
					while(!mIsReceive) {
						if(stop) {
							break;
						}
						
						SystemClock.sleep(10);
					}
					
					SystemClock.sleep(1000);
				}
				
				mCount++;
				
				mIsReceive = false;
				mResult = 0;
				
				if(mCount == mTotal) {
					if(lastCheck != null) {
						sms.sendTextMessage(lastCheck, null, text, mSendPI, null);
						Log.d("test", mCount+"::lastCheck");
					}
					break;
				} else {
					if(mCount%page==0) {
						if(onceCheck != null) {
							sms.sendTextMessage(onceCheck, null, text, mSendPI, null);
							Log.d("test", mCount+"::onceCheck");
						}
					}
				}
				
			}
			return null;
		} 
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			
			editCurrentCount.setText(String.valueOf(values[0]));
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
		}
		
		public void stop() {
			stop = true;
		}
	}
	
	private class MMSSendThread extends AsyncTask<String, Integer, Integer> {
		private boolean stop = false;
		
		@Override
		protected Integer doInBackground(String... params) {
			// TODO Auto-generated method stub
			MMS mms = new MMS(getApplicationContext());
			String text = editSendView.getText().toString();
			String onceCheck = null;
			String lastCheck = null;
			
			if(mLastCheck) {
				lastCheck = editLastCheck.getText().toString();
			}
			if(mOnceCheck) {
				onceCheck = editOnceCheck.getText().toString();
			}
			
			int page = Integer.valueOf(editOnceCount.getText().toString());
			
			while(!stop) {
				Log.d("test", mCount+"::PhoneBook");
//				String[] numbers;
//				if(mTotal - mCount < MMS_RANGE) {
//					numbers = new String[mTotal - mCount];
//				} else {
//					numbers = new String[MMS_RANGE];
//				}
//				
//				for(int i=0; i<numbers.length; i++) {
//					String num = Const.PhoneBook.get(mCount++);
//					num = "+82" + num.substring(1);
//					
//					numbers[i] = num;
//				}
				
				mms.sendMMS(Const.PhoneBook.get(mCount++), mImageCaptureUri, text, mCount);
				
				publishProgress(mCount);
				
				if((mCount > 0) && (mCount % CHECK_COUNT == 0)) {
					SystemClock.sleep(1000);
				}
				
				mIsReceive = false;
				mResult = 0;
				
				if(mCount == mTotal) {
					if(lastCheck != null) {
						mms.sendMMS(lastCheck, mImageCaptureUri, text, mCount);
						Log.d("test", mCount+"::lastCheck");
					}
					break;
				} else {
					if(mCount%page==0) {
						if(onceCheck != null) {
							mms.sendMMS(onceCheck, mImageCaptureUri, text, mCount);
							Log.d("test", mCount+"::onceCheck");
						}
					}
				}
			}
			return null;
		} 
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			
			editCurrentCount.setText(String.valueOf(values[0]));
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
		}
		
		public void stop() {
			stop = true;
		}
	}
}
